<template>
  <view class="property-value-form">
    <uni-nav-bar
      :title="formTitle"
      left-icon="back"
      @clickLeft="handleBack"
    />
    
    <uni-card>
      <uni-forms :model="formData" :rules="formRules">
        <uni-forms-item label="属性值" required name="name">
          <uni-easyinput v-model="formData.name" placeholder="请输入属性值" />
        </uni-forms-item>
        <uni-forms-item label="备注" name="remark">
          <uni-easyinput v-model="formData.remark" placeholder="请输入备注" />
        </uni-forms-item>
        
        <button type="primary" class="submit-btn" @click="submitForm">提交</button>
      </uni-forms>
    </uni-card>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { 
  createPropertyValue,
  updatePropertyValue
} from '@/api/mall/product/property'

const formData = ref({
  id: null,
  propertyId: null,
  name: '',
  remark: ''
})

const formMode = ref('create')

const formTitle = computed(() => formMode.value === 'create' ? '添加属性值' : '编辑属性值')

const formRules = {
  name: {
    rules: [{ required: true, errorMessage: '请输入属性值' }]
  }
}

onLoad((options) => {
  console.log('options:', options)
  if (options.mode) {
    formMode.value = options.mode
    //formData.value = { ...value }
  }
  if (options.name) {
    formData.value.name = options.name
  }
  if (options.id) {
    formData.value.id = options.id
  }

  if (options.remark) {
    formData.value.remark = options.remark
  }

  if (options.propertyId) {
    formData.value.propertyId = options.propertyId
  }
  // if (options.value) {
  //   const value = JSON.parse(options.value)
  //   formData.value = { ...value }
  //   console.log(' formData.value:',  formData.value)
  // }
})

const submitForm = async () => {
  try {
    if (formMode.value === 'create') {
      await createPropertyValue(formData.value)
    } else {
      await updatePropertyValue(formData.value)
    }
    uni.showToast({ title: '操作成功', icon: 'success' })
     uni.navigateBack()
       // 触发刷新事件
    uni.$emit('refreshPropertyValues', {id: formData.value.propertyId})
    
     
  } catch (e) {
    console.error(e)
  }
}

const handleBack = () => {
  uni.navigateBack()
}
</script>

<style scoped>
.property-value-form {
  padding: 15px;
}

.submit-btn {
  margin-top: 15px;
  width: 100%;
}
</style>